package com.example.monthdateselector;

import hirondelle.date4j.DateTime;

import java.util.TreeMap;

public class RangeTreeMap extends TreeMap<String, Range> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	public boolean insert(Range r){
		if(canInsert(r)){
			put(getKeyFromCalDayItem(r), r);
			return true;
		}
		return false;
		
	}
	
	public boolean canInsert(Range r){
		if(r!=null&&r.getStart()!=null){
			//是否有重复
			Range previRange=previRange(r);
			System.out.println("prevR:"+(previRange==null?"prevR is null":previRange.toString()));
			if(previRange!=null&&previRange.getEnd().gteq(r.getStart())){
				return false;
			}
			
			Range nextRange=nextRange(r);
			System.out.println("nextR:"+(nextRange==null?"nextR is null":nextRange.toString()));
			
				if(nextRange!=null&&nextRange.getStart().lteq(r.getEnd())){
				return false;
			}
			return true;
		}
		return false;
	}
	
	public void del(Range r){
		if(r!=null&&r.getStart()!=null){
			remove(getKeyFromCalDayItem(r));
		}
	}
	
	/**r的日期以后的range*/
	public Range nextRange(Range r){
		Entry<String, Range> entry = ceilingEntry(getKeyFromCalDayItem(r));
		if(entry!=null){
			return entry.getValue();
		}else{
			return null;
		}
	}
	/**r的日期以前的range*/
	public Range previRange(Range r){
		Entry<String, Range> entry = floorEntry(getKeyFromCalDayItem(r));
		if(entry!=null){
			return entry.getValue();
		}else{
			return null;
		}
	}
	
	public Range getRange(DateTime d){
		if(d!=null){
			return get(getKey(d));
		}
		return null;
	}
	
	private String getKeyFromCalDayItem(Range r){
		return getKey(r.getStart());
	}
	private String getKey(DateTime d){
		return d.format("YYYY-MM-DD");
	}
	
}
